//
//  API_AsyncSequence_Demo2VC.swift
//  APSwift
//
//  Created by jianbo.pei on 2024/8/16.
//

import UIKit

class API_AsyncSequence_Demo2VC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        /// 使用 `for await` 语法来遍历 `Counter`
        Task {
            for await number in Counter(howHigh: 10) {
                print(number, terminator: " ")
            }
            print("Counting finished!")
        }
    }

}

/// 定义一个异步计数器序列
struct Counter: AsyncSequence {
//    typealias AsyncIterator = CounterIterator
    typealias Element = Int
    
    let howHigh: Int
    
    func makeAsyncIterator() -> CounterIterator {
        return CounterIterator(howHigh: howHigh)
    }
}

/// 定义计数器的异步迭代器
struct CounterIterator: AsyncIteratorProtocol {
//    typealias Element = Int
    
    let howHigh: Int
    var current: Int = 1
    
    mutating func next() async -> Int? {
        guard current <= howHigh else {
            return nil
        }
        
        let value = current
        current += 1
        
        /// 模拟异步操作延迟: 0.5 秒延迟
        try? await Task.sleep(nanoseconds: 500_000_000)
        
        return value
    }
}


